package cn.client.ui.view.main.chat

import android.widget.Toast
import androidx.annotation.DrawableRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Divider
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import cn.client.MainViewModel
import cn.client.R
import cn.client.data.ChatData
import cn.client.data.MsgDataItem
import cn.client.data.Person
import cn.client.data.UserStateManager
import cn.client.data.userStateManager
import cn.client.navigation.destinations.FriendHost

/**
 *消息列表
 */
@Composable
fun ChatList(
    navController: NavController,
    onClickChat: (Int, Int) -> Unit = { _, _ -> },
    mainViewModel: MainViewModel = hiltViewModel()
) {
    val context = LocalContext.current
    // 使用 collectAsState 观察 userId 的变化
    val userIdState = userStateManager.userId.collectAsState(initial = -1)
    val userId = userIdState.value

    val onConnectState = mainViewModel.onConnect.collectAsState(initial = false)
    val onConnect = onConnectState.value

    val chats = mainViewModel.chats

    if (userId == -1) {
        mainViewModel.dispatch(MainViewModel.PageIntent.GetUser("获取本地用户缓存"))
    }
    if (userId != -1 || !onConnect) {

        Toast.makeText(context, "提示：已连接", Toast.LENGTH_SHORT).show()
    }

    /**
     * 观察连接状态
     */

    LaunchedEffect(Unit) {
        // 实时监听接收的消息，即 数据库发生的变化
        mainViewModel.pageEvents.collect { it ->
            when (it) {
                is MainViewModel.PageEvent.WebSocketMiss -> {
                    Toast.makeText(context, "提示：${it.msg}", Toast.LENGTH_SHORT).show()
                }
                else -> {}
            }
        }
    }


    /* 顶部导航栏 */
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)
    ) {

        ChatListTopAppBar(
            onClickFriendList = {
                navController.navigate(FriendHost.route)
            }
        )
        LazyColumn {
            itemsIndexed(chats){index: Int, it: ChatData ->
                ChatItem(chat = it,
                    onclickStarChat = {
                        onClickChat(userId, it.person.id)
                    })
                if (index < chats.lastIndex){
                    Divider(
                        startIndent = 68.dp,
                        color =Color.LightGray,
                        thickness = 0.8f.dp
                    )
                }
            }
        }
    }
}



// 聊天item
// 用户名、头像、最后一条消息、消息时间
@Composable
fun ChatItem(
    chat: ChatData,
    onclickStarChat: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable {
                /* TODO: 进入聊天页面 */
                onclickStarChat()
            }
    ) {
        // 头像
        Image(
            painter = painterResource(chat.person.avatar),
            contentDescription = null,
            contentScale = ContentScale.Crop,
            modifier = Modifier
                .padding(5.dp)
                .unread(!chat.msg.last().read, Color.Red)
                .size(50.dp)
                .border(1.dp, MaterialTheme.colorScheme.primary, CircleShape)
                .clip(CircleShape)
        )
        // 好友名称和最后一条消息
        Column(
            modifier = Modifier
                .weight(1f)
                .align(Alignment.CenterVertically)
        ) {
            Text(text = chat.person.name, fontSize = 17.sp, color = Color.DarkGray)
            Text(text = chat.msg.last().text, fontSize = 14.sp, color = Color.Gray)
        }
        // 日期
        Text(
            text = chat.msg.last().time,
            Modifier.padding(8.dp, 8.dp, 12.dp, 8.dp),
            fontSize = 11.sp, color = Color.Gray
        )
    }
}


// 顶部栏
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ChatListTopAppBar(
    onClickFriendList: () -> Unit
) {
    TopAppBar(
        colors = TopAppBarDefaults.topAppBarColors(
            containerColor = MaterialTheme.colorScheme.primaryContainer,
            titleContentColor = MaterialTheme.colorScheme.primary
        ),
        title = { Text("消息列表") },
        /* 左边按钮 */
        navigationIcon = {
            IconButton(onClick = {
                /*  跳转到好友列表 */
                onClickFriendList()
            }) {
                Icon(
                    painter = painterResource(
                        R.drawable.ic_address_book
                    ), null
                )
            }
        },
        /* 右边按钮（可以是多个） */
        actions = { IconButton(onClick = { }) { Icon(Icons.Filled.MoreVert, null) } }
    )
}

// 小红点
fun Modifier.unread(show: Boolean, color: Color): Modifier = this.drawWithContent {
    drawContent()
    if (show) {
        drawCircle(color, 5.dp.toPx(), Offset(size.width - 1.dp.toPx(), 1.dp.toPx()))
    }
}